package top.gokzzz.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring 工具類
 *
 * @author Gok
 * @version 1.1
 */
@Component
public class SpringUtil implements BeanFactoryPostProcessor, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * "@PostConstruct" 注解标记的类中，由于 ApplicationContext 还未加载，导致空指针
     */
    private static ConfigurableListableBeanFactory configurableListableBeanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        SpringUtil.configurableListableBeanFactory = configurableListableBeanFactory;
    }

    public static ListableBeanFactory getBeanFactory() {
        final ListableBeanFactory factory = null == configurableListableBeanFactory ? applicationContext : configurableListableBeanFactory;
        if (null == factory) {
            throw new RuntimeException("No ConfigurableListableBeanFactory or ApplicationContext injected");
        }
        return factory;
    }

    /**
     * 通過 name 獲取 bean
     *
     * @param name bean 名稱
     * @return Bean 對象
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) getBeanFactory().getBean(name);
    }

    /**
     * 通过 class 获取Bean
     *
     * @param clazz bean 類
     * @return Bean 對象
     */
    public static <T> T getBean(Class<T> clazz) {
        return getBeanFactory().getBean(clazz);
    }
}
